class Solution {
  public:
    bool isBalanced(TreeNode* root) {
        if (getdepth(root) != -1) {
            return true;
        } else {
            return false;
        }
    }
    int getdepth(TreeNode* node) {
        if (node == NULL) {
            return 0;
        }
        int leftlength = getdepth(node->left);
        int rightlength = getdepth(node->right);
        if (leftlength == -1) {
            return -1;
        }
        if (rightlength == -1) {
            return -1;
        }
        if (abs(leftlength - rightlength) > 1) {
            return -1;
        } else {
            return max(leftlength, rightlength) + 1;
        }
    }
};